<template>
  <div :id="propId" :ref="propRef" class="chart"></div>
</template>

<script>
import axios from "axios";
import waterColors from "@/utils/waterColor.js";
// 用于绘制瀑布图、罗盘图、折线图的完整版js
import chart from "@/utils/chart.js";
export default {
  name: "PuBuChart",
  props: ["propId", "propRef", "url"],
  data() {
    return {
      // 瀑布图图表对象
      chart: null,
      // 瀑布图系列(坐标轴)对象
      series: null,
      maxVal: null, // 传入一组数据的最大值
      minVal: null, // 传入一组数据的最小值
      xAxisMin: 0,
      xAxisMax: 100,
      initXAxisMin: null,
      initXAxisMax: null,
      pointNum: 10242, // 瀑布图列数
      xInterval: [], // x坐标起始区间
      lastTime: null,
      fpstmp: null,
      fps: null,
      timestamps: [],
      pubuxValue: "",
      pubuyValue: "",
      pubuzValue: "",
      timerFlag: null, // 抽点用的防抖函数的延时器id
    };
  },
  mounted() {
    this.initPubu();
  },
  inject: ["userMark"],
  beforeDestroy() {
    this.chart = null;
    clearTimeout(this.timerFlag);
    this.timerFlag = null;
  },
  methods: {
    // 初始化瀑布图
    initPubu() {
      const that = this;
      that.chart = chart().pubu({
        container: that.propId,
        background: {
          r: 60 / 255,
          g: 60 / 255,
          b: 60 / 255,
        },
      });
      // 设置瀑布图坐标基本样式和配置
      that.series = that.chart.addSeries({
        title: {
          text: "瀑布图",
          left: that.$refs[that.propRef].clientWidth / 2,
          top: 10,
        },
        // x轴单位
        axisXUnits: {
          text: "频率/MHz",
          left: that.$refs[that.propRef].clientWidth / 2,
          top: that.$refs[that.propRef].clientHeight,
        },
        // y轴单位
        axisYUnits: {
          text: "时间/Times",
          left: 5,
          top: that.$refs[that.propRef].clientHeight / 2,
        },
        // x轴标点数量
        xAxisMarkNum: 10,
        // y轴标点数量
        yAxisMarkNum: 5,
        // 行高 => 影响着瀑布图下刷的速度
        row: 100,
        // 列宽
        column: that.pointNum,
        // y轴左边距
        yAxisPadding: 75,
        // y轴右边距
        yAxisAnotherPadding: 20,
        // x轴下边距
        xAxisPadding: 40,
        // x轴上边距
        xAxisAnotherPadding: 30,
        // x轴坐标格式化
        xAxisMarkFormatter: (value) => {
          return Number(value / 1000).toFixed(2);
        },
        // 坐标轴颜色
        axisColor: {
          r: 192 / 255,
          g: 224 / 255,
          b: 224 / 255,
        },
        showColors: true, // 显示颜色刻度
        // showAllData: true // 是否显示所有的列，设置为true的时候不对column做处理，相当于此时在抽点
        // x轴最小刻度
        // minXInterval: 200
      });

      that.series.setColors(waterColors.sixColors());
      that.series.setValueInterval(-110, -50);
      // 设置瀑布图X轴最大区间 => 不配置的话默认设置为 [0, 100]
      // that.series.setMaxXInterval([that.xAxisMin, that.xAxisMax]);

      // 设置瀑布图X轴区间变化时的回调函数 => 变化时折线图x轴区间跟着变化同时刷新图表
      that.series.setOnXIntervalChange((newInterval) => {
        /* // 使用防抖函数，使其在缩放结束0.3s后再去调接口改数据
        that.timerFlag && clearTimeout(that.timerFlag);
        that.timerFlag = setTimeout(async () => {
          // 设置折线图x轴当前区间
          // that.series.changeXInterval(newInterval)
          // that.pubuxInterval = newInterval;
          // that.chart.refresh();

          try {
            await this.setRangeAPI({
              from: newInterval[0],
              end: newInterval[1],
              // userName: "1_" + this.userMark,
              userName: "1_123456789",
            });
          } catch (error) {
            console.log(error);
          }
        }, 300); */
      });
      // 给瀑布图添加鼠标移动事件
      that.series.setOnMouseMoveListener((x, y, event) => {
        // debugger
        const date = new Date(y);
        const hour =
          date.getHours().toString().length > 1
            ? date.getHours()
            : "0" + date.getHours();
        const minutes =
          date.getMinutes().toString().length > 1
            ? date.getMinutes()
            : "0" + date.getMinutes();
        const seconds =
          date.getSeconds().toString().length > 1
            ? date.getSeconds()
            : "0" + date.getSeconds();
        const str = hour + ":" + minutes + ":" + seconds;
        that.pubuxValue = x.toFixed(2);
        that.pubuyValue = str;
        if (that.pubuyValue) {
          that.pubuzValue = that.series.getYData(that.pubuxValue);
          if (that.pubuzValue !== null && that.pubuzValue !==NaN) {
            // console.log(
            //   "瀑布图鼠标当前位置:",
            //   that.pubuxValue,
            //   that.pubuzValue
            // );
            that.series.addTooltip({
              value1: that.pubuxValue / 1000,
              value2: that.pubuzValue,
              left: that.$refs[that.propRef].clientWidth,
              top: 10,
            });
          }
        }
      });
      // 给瀑布图添加点击事件
      that.series.setOnClickListener((x, y, event) => {
        // let date = new Date(y);
        // let hour =
        //   date.getHours().toString().length > 1
        //     ? date.getHours()
        //     : "0" + date.getHours();
        // let minutes =
        //   date.getMinutes().toString().length > 1
        //     ? date.getMinutes()
        //     : "0" + date.getMinutes();
        // let seconds =
        //   date.getSeconds().toString().length > 1
        //     ? date.getSeconds()
        //     : "0" + date.getSeconds();
        // let str = hour + ":" + minutes + ":" + seconds;
        // that.pubuxClickValue = x.toFixed(2);
        // that.pubuyClickValue = str;
        // console.log("瀑布图鼠标当前位置:", x, y);
      });

      that.series.setOnMeasureListener((startX, startY, endX, endY) => {
        let date = new Date(startY);
        let hour =
          date.getHours().toString().length > 1
            ? date.getHours()
            : "0" + date.getHours();
        let minutes =
          date.getMinutes().toString().length > 1
            ? date.getMinutes()
            : "0" + date.getMinutes();
        let seconds =
          date.getSeconds().toString().length > 1
            ? date.getSeconds()
            : "0" + date.getSeconds();
        const startstr = hour + ":" + minutes + ":" + seconds;
        date = new Date(endY);
        hour =
          date.getHours().toString().length > 1
            ? date.getHours()
            : "0" + date.getHours();
        minutes =
          date.getMinutes().toString().length > 1
            ? date.getMinutes()
            : "0" + date.getMinutes();
        seconds =
          date.getSeconds().toString().length > 1
            ? date.getSeconds()
            : "0" + date.getSeconds();
        const endstr = hour + ":" + minutes + ":" + seconds;
        that.pubustartX = startX.toFixed(2);
        that.pubustartY = startstr;
        that.pubuendX = endX.toFixed(2);
        that.pubuendY = endstr;
      });

      that.chart.refresh();
    },
    // 绘图的方法
    drawChart(yData, startFreq, endFreq, initStart, initEnd) {
      if (yData.length && yData.length >= 65536) return;

      if (this.initXAxisMin !== initStart || this.initXAxisMax !== initEnd) {
        this.initXAxisMin = initStart;
        this.initXAxisMax = initEnd;
        // 重新设置折线图/瀑布图x轴最大区间
        this.changeMaxInterval();
      }

      if (this.xAxisMax !== endFreq || this.xAxisMin !== startFreq) {
        this.xAxisMin = startFreq;
        this.xAxisMax = endFreq;
        // 重新设置折线图/瀑布图x轴当前区间
        this.changeInterval();
      }

      /* if (
        this.xAxisMin === this.initXAxisMin &&
        this.xAxisMax === this.initXAxisMax
      ) {
        // 没有抽点
        this.changeShowAllData(false);
      } else {
        // 抽点了
        this.changeShowAllData(true);
      } */

      if (yData.length !== this.pointNum) {
        this.pointNum = yData.length;
        this.series.setColumn(this.pointNum);
      }
      // 计算数据的最大最小值来控制瀑布图按值渲染不同颜色
      // const max = Math.max.apply(null, yData)
      // const min = Math.min.apply(null, yData)
      const max = Math.max(...yData);
      const min = Math.min(...yData);
      this.maxVal = max;
      this.minVal = min;

      // 获取时间戳作为Y轴坐标传入
      const timestamp = new Date().getTime();

      // 瀑布图添加数据 => 添加之前先根据最大最小值改变不同范围下的值的颜色显示
      // this.series2.setValueInterval(this.minVal, this.maxVal)
      // this.series.setValueInterval(-110, -50);
      // console.log("max", this.maxVal, "min", this.minVal);

      const temArr = [];
      const increase = (endFreq - startFreq) / yData.length;

      yData.forEach((item, index) => {
        // 填入频谱图数据
        temArr.push(startFreq + index * increase);
        temArr.push(item);
      });

      // console.log(this.xAxisMin, this.xAxisMax, this.minVal, this.maxVal)
      // console.log('瀑布图实时数据:', temArr)
      this.series.addRowData(temArr, timestamp);

      if (!this.timestamps) {
        this.timestamps = [];
      }
      this.timestamps.push(timestamp);
      if (this.timestamps.length > 61) {
        this.timestamps.splice(0, 1);
      }
      this.chart.refresh();
      const now = new Date().getTime();
      if (this.lastTime) {
        if (now - this.lastTime > 1000) {
          this.fps = this.fpstmp + "";
          this.lastTime = new Date().getTime();
          this.fpstmp = 0;
        } else {
          this.fpstmp++;
        }
      } else {
        this.lastTime = new Date().getTime();
        this.fpstmp = 0;
      }
    },

    // 设置折线/瀑布图X轴当前区间
    changeInterval() {
      this.series.setMaxXInterval([this.xAxisMin, this.xAxisMax]);
    },
    // 设置折线/瀑布图X轴最大区间
    changeMaxInterval() {
      if (this.initXAxisMin !== null) {
        this.series.setMaxXInterval([this.initXAxisMin, this.initXAxisMax]);
      } else {
        this.series.setMaxXInterval([this.xAxisMin, this.xAxisMax]);
      }
    },
    // 是否展示所有数据 => 针对瀑布图
    changeShowAllData(bool) {
      this.series.changeShowAllData(bool);
    },
    setRangeAPI(data) {
      let url;
      if (this.propRef === "canvas1" || this.propRef === "canvas2") {
        url = this.url[0];
      } else {
        url = this.url[1];
      }
      return axios({
        url: "http://" + url + "/interface/range/set",
        method: "post",
        data,
      });
    },
  },
};
</script>

<style lang="scss" scoped>

</style>
